import React, { Component } from 'react';
import { Button, Spin, Input, Table, Modal, Space } from 'antd';
import {
    getCrmByParam,
    getCrmRecordFromSql,
    isBlank
} from "../util/util";
import { SearchOutlined } from "@ant-design/icons";

const ZOHO = window.ZOHO;

class LinkingModule9 extends Component {
    constructor(props) {
        super(props);
        this.state = {
            user: {},
            loading: false,
            modalVisible: false,
            screenHeight: window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight,
            selectedContractRowKeys: [],
            contractColumns: [{
                title: '外销合同号',
                dataIndex: 'Subject',
                key: 'Subject',
                type: 'text',
                ...this.getColumnSearchProps('Subject'),

            }, {
                title: '客户简称',
                dataIndex: 'customername',
                key: 'customername',
                type: 'text',
                ...this.getColumnSearchProps('Account_Name'),

            }, {
                title: '客户订单号',
                dataIndex: 'AccountOrderNo',
                key: 'AccountOrderNo',
                type: 'text',
                ...this.getColumnSearchProps('AccountOrderNo'),

            },],
            contactData: [],
            column: [{
                title: '商品库名称',
                dataIndex: 'Product',
                key: 'Product',
            }, {
                title: '内部代码',
                dataIndex: 'internalcode',
                key: 'internalcode',
            }, {
                title: '合同号',
                dataIndex: 'Subject',
                key: 'Subject',
            }, {
                title: '客户订单号',
                dataIndex: 'AccountOrderNo',
                key: 'AccountOrderNo',
            }, {
                title: '合同数量',
                dataIndex: 'Quantity',
                key: 'Quantity',
            }, {
                title: '未备货数量',
                dataIndex: 'StockQty',
                key: 'StockQty',
            },],
            dataSource: [],
            selectedRowKeys: [],
            searchInput: [],
        };
    }

    async componentDidMount() {
        this.setState({ loading: true })
        let user = {};
        ZOHO.CRM.UI.Resize({ height: "2000", width: "2000" }).then(function (data) {
            console.log(data);
        });
        await ZOHO.CRM.CONFIG.getCurrentUser().then(function (data) {
            user = data.users[0]
        });

        let selectedRowKeys = [];
        let selectedContractRowKeys = [];
        let dataSource = [];
        let contactData = [];

        if (!isBlank(window.data)) {
            let data = window.data
            console.log(data)
            if (isBlank(data.Account)) {
                Modal.error({
                    title: '请先选择客户',
                    content: '请先选择客户',
                    okText: '确定',
                    onOk: () => {
                        ZOHO.CRM.UI.Popup.close().then(() => {

                        });
                    }
                });
                return
            }
            if (isBlank(data.ShipperInformation)) {
                Modal.error({
                    title: '请先选择发货人',
                    content: '请先选择发货人',
                    okText: '确定',
                    onOk: () => {
                        ZOHO.CRM.UI.Popup.close().then(() => {

                        });
                    }
                });
                return
            }
            if (!isBlank(data.id1)) {
                selectedContractRowKeys = data.id1.split(",")
            }
            selectedRowKeys = data.LinkingModule9?.map(item => {
                return item.id1;
            })
            console.log(selectedRowKeys)
            console.log(selectedContractRowKeys)
            try {
                let fields = ['Subject', 'DeliveryDate', 'ContractDate', 'PayMethod', 'AccountOrderNo', 'ContractItem',
                    'Quote_Name', 'Header', 'ContractType', 'TransactionMethod', 'ShipperInformationName', 'OverShort_Shipment',
                    'Account_Name', 'Account_Name.Account_Name as customername', 'EstimatedShippingDate', 'Deal_Name', 'Currency', 'Account', 'Modified_By',
                    'ShippingPort', 'Buttonchange', 'DestinationPort', 'Created_Time', 'Modified_Time', 'Created_By', 'Owner',
                    'Terms_and_Conditions', 'Post_Contractual_Terms', 'Description', 'Sub_Total', 'Discount', 'Tax', 'Adjustment',
                    'Grand_Total', 'SumStockQty	', 'Header.Name as Headername'];
                var sql1 = `select ${fields} from Sales_Orders where ((SumStockQty >0 and Owner = ${user.id}) and Account_Name = ${window.data.Account.id}) and field2 = '审批通过'`;
                console.log("sql1", sql1)

                contactData = await getCrmRecordFromSql(sql1);
                console.log(111, contactData)
            } catch (e) {
                console.error(e)
            }

            try {
                if (selectedContractRowKeys.length > 0) {
                    dataSource = await getCrmRecordFromSql(`select 
        Parent_Id.Subject as Subject,Product_Name.id as productid,Product_Name.Product_Name as Product,id,internalcode
        ,Quantity,Parent_Id.AccountOrderNo as AccountOrderNo ,AccountprtNo,Chinesespecification,Chptrequirements_material,Chineseingredients,
        Brand,Englishname,Specification,Nuofboxesinpg,Nuofboxeinnerbox,Lengthofouterbox,Heightofouterbox,Grossweight,NumberofCartons,Parent_Id.EstimatedShippingDate as EstimatedShippingDate,
        Cartonwidth,Netweight,Volume,StockQty,List_Price,Productname,Packagingquantityperpg,Category,Parent_Id,Parent_Id.ContractDate as ContractDate,
        Parent_Id.ContractItem as ContractItem,Parent_Id.Terms_and_Conditions as Terms_and_Conditions,Parent_Id.Currency as Currency,ChinesePackagedesp,ShippingMark,
        Parent_Id.ShippingPort,Parent_Id.DestinationPort,W,Unit,Packaginunit,HSCode
        Parent_Id.PayMethod as PayMethod,Parent_Id.TransactionMethod as TransactionMethod
                from Ordered_Items where Parent_Id in (${selectedContractRowKeys}) and StockQty>0 `);
                    console.log(dataSource)
                }
            } catch (e) {
                console.error(e)
            }


        }

        console.log(user)
        this.setState({
            user: user,
            selectedRowKeys: selectedRowKeys,
            selectedContractRowKeys: selectedContractRowKeys,
            dataSource: dataSource,
            loading: false,
            modalVisible: true,
            contactData: contactData
        });
    }

    handleSave = async () => {
        this.setState({ loading: true });
        const { selectedRowKeys, dataSource, contactData } = this.state
        const LinkingModule9 = [];
        let selectData = [];
        dataSource.forEach(item => {
            if (selectedRowKeys.includes(item.id)) {
                selectData.push(item)
                // 总毛重 = ${产品信息.毛重(KG)}*(${产品信息.数量}/${产品信息.每箱装量})
                const TotalGrossWeight = item.Packagingquantityperpg === 0 ? 0 : (item.Grossweight * (item.StockQty / item.Packagingquantityperpg));
                // 总体积=((${产品信息.长(CM)}*${产品信息.宽(CM)}*${产品信息.高(CM)})/1000000)*(${产品信息.数量}/${产品信息.每箱装量})
                // const TotalVolume = ((Lengthofouterbox * Cartonwidth * Heightofouterbox) / 1000000) * (Qty / QuantityperCarton);
                const TotalVolume = item.Packagingquantityperpg === 0
                    ? 0
                    : ((item.Lengthofouterbox * item.Cartonwidth * item.Heightofouterbox) / 1000000) * (item.StockQty / item.Packagingquantityperpg);
                // console.log('TotalGrossWeight',TotalGrossWeight);
                // console.log('TotalVolume',TotalVolume);
                LinkingModule9.push({

                    OrderNo: item.AccountOrderNo,
                    Product: {
                        id: item.productid,
                        name: item.Product
                    },
                    AccountprtNo: item.AccountprtNo,
                    internalcode: item.internalcode,
                    Englishname: item.Englishname,
                    Specification: item.Specification,
                    Brand: item.Brand,
                    Unit_Price: item.List_Price,
                    Unit: item.Unit,
                    Packaginunit: item.Packaginunit,
                    NumberofCartons: item.NumberofCartons,
                    Lengthofouterbox: item.Lengthofouterbox,
                    Heightofouterbox: item.Heightofouterbox,
                    Cartonwidth: item.Cartonwidth,
                    QuantityperCarton: item.Packagingquantityperpg,
                    Netweight: item.Netweight,
                    Category: item.Category,
                    Productname: item.Productname,
                    TotalVolume: TotalVolume,
                    TotalGrossWeight: TotalGrossWeight,
                    ChinesePackagedesp: item.ChinesePackagedesp,
                    Chptrequirements_material: item.Chptrequirements_material,
                    Chinesespecification: item.Chinesespecification,
                    Chineseingredients: item.Chineseingredients,
                    Nuofboxesinpg: item.Nuofboxesinpg,
                    Nuofboxeinnerbox: item.Nuofboxeinnerbox,
                    ForeignsacontractNo: item.Subject,
                    Grossweight: item.Grossweight,
                    TotalNetweight: item.TotalNetWeight,
                    Qty: item.StockQty,
                    id1: item.id,
                    ShippingMark: item.ShippingMark,
                    PSNoticeNo: item.W,
                    HSCode: item.HSCode
                })
            }
        });

        console.log('LinkingModule9',JSON.stringify(LinkingModule9))

        try {
            let selectContactData = dataSource[0];

            //取货好时间
            let firstFcontractNos = selectData[0]?.Subject;
            console.log('firstFcontractNos', firstFcontractNos);
            var Deliverytime = null;
            if (!isBlank(firstFcontractNos)) {
                let PSNotice = await getCrmRecordFromSql(`select Deliverytime,id from PSNotice where Exportcontractnumber like '%${firstFcontractNos}%' `);
                console.log("PSNotice", PSNotice);
                if (PSNotice && PSNotice.length > 0) {
                    console.log("PSNotice", JSON.stringify(PSNotice[0]));
                    Deliverytime = PSNotice[0].Deliverytime;
                }
            }

            // await ZOHO.CRM.UI.Record.populate({
            //     LinkingModule9: [],
            //     ContractDate: null,
            //     ProcurementTerms: null,
            //     AccountOrderNo: null,
            //     Currency: null,
            //     ShippingPort: null,
            //     DestinationPort: null,
            //     TransactionMethod: null,
            //     PayMethod: null,
            //     Deliverytime: null,
            // })
            let Subjects = [];
            let id1 = [];
            selectData.forEach(item => {
                if (!id1.includes(item.Parent_Id.id)) {
                    id1.push(item.Parent_Id.id)
                    Subjects.push(item.Subject)
                }
            })
            const AllContractItem = [...new Set(dataSource
                .map(item => item.ContractItem) // Extract the 'ContractItem' property from each object
                .filter(Boolean)                // Filter out falsy values (null, undefined, '', 0, false)
            )].join('/');                       // Join the unique values with a slash ('/')

            // await new Promise(resolve => setTimeout(resolve, 800));  

            // let linkingModule9Objects = LinkingModule9.map(() => ({ AccountprtNo: null }));

            await ZOHO.CRM.UI.Record.populate({
                LinkingModule9:LinkingModule9
            });
            // await new Promise(resolve => setTimeout(resolve, 800));  

            console.log('selectContactData', JSON.stringify(selectContactData));

            await ZOHO.CRM.UI.Record.populate({
                LinkingModule9: LinkingModule9,
                ContractDate: selectContactData.ContractDate,
                ProcurementTerms: selectContactData.Terms_and_Conditions,
                AccountOrderNo: selectContactData.AccountOrderNo,
                FcontractNos: Subjects.toString().replaceAll(",", "/"),
                Currency: selectContactData.Currency,
                ShippingPort: {
                    id: selectContactData.ShippingPort?.id,
                    name: selectContactData.ShippingPortName
                },
                DestinationPort: {
                    id: selectContactData.DestinationPort?.id,
                    name: selectContactData.DestinationPortName
                },
                TransactionMethod: selectContactData.TransactionMethod,
                PayMethod: selectContactData.PayMethod,
                Deliverytime: Deliverytime,
                EstimatedShippingDate: selectContactData.EstimatedShippingDate,
                AllContractItem: AllContractItem,
            })

        } catch (e) {
            console.log(e)
        }finally{
            await ZOHO.CRM.UI.Popup.close().then(() => {
                this.setState({ loading: false });
            });
        }

    };

    handleModalClose = () => {
        this.setState({ modalVisible: false })
    };

    handleOkModal = async () => {
        const { selectedContractRowKeys } = this.state
        console.log(selectedContractRowKeys)
        let crmRecordFromSql = await getCrmRecordFromSql(`select 
        Parent_Id.Subject as Subject,Product_Name.id as productid,Product_Name.Product_Name as Product,id,internalcode,Parent_Id.EstimatedShippingDate as EstimatedShippingDate
        ,Quantity,Parent_Id.AccountOrderNo as AccountOrderNo ,AccountprtNo,Chinesespecification,Chptrequirements_material,Chineseingredients,
        Brand,Englishname,Specification,Nuofboxesinpg,Nuofboxeinnerbox,Lengthofouterbox,Heightofouterbox,Grossweight,NumberofCartons,
        Cartonwidth,Netweight,Volume,StockQty,List_Price,Productname,Packagingquantityperpg,Category,Parent_Id,Parent_Id.ContractDate as ContractDate,
        Parent_Id.Terms_and_Conditions as Terms_and_Conditions,Parent_Id.Currency as Currency,ChinesePackagedesp,ShippingMark,Parent_Id.ContractItem as ContractItem,
        Parent_Id.ShippingPort as ShippingPort,Parent_Id.DestinationPort as DestinationPort,Parent_Id.ShippingPort.Name as ShippingPortName ,Parent_Id.DestinationPort.Name as DestinationPortName,W,
         Unit,Packaginunit,HSCode,
         Parent_Id.PayMethod as PayMethod,Parent_Id.TransactionMethod as TransactionMethod
        from Ordered_Items where Parent_Id in (${selectedContractRowKeys}) and StockQty>0 `);
        console.log(crmRecordFromSql)

        this.setState({ modalVisible: false, dataSource: crmRecordFromSql })

    };

    onContractSelectChange = (newselectedRowKeys) => {
        console.log(newselectedRowKeys)
        this.setState({ selectedContractRowKeys: newselectedRowKeys });
    };

    onSelectChange = (newselectedRowKeys) => {

        this.setState({ selectedRowKeys: newselectedRowKeys });
    };
    getColumnSearchProps = (dataIndex) => ({
        filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters, close }) => (
            <div
                style={{
                    padding: 8,
                }}
                onKeyDown={(e) => e.stopPropagation()}
            >
                <Input
                    placeholder={`Search ${dataIndex}`}
                    value={selectedKeys[0]}
                    onChange={(e) => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                    onPressEnter={() => this.handleSearch(selectedKeys, confirm, dataIndex)}
                    style={{
                        marginBottom: 8,
                        display: 'block',
                    }}
                />
                <Space>
                    <Button
                        type="primary"
                        onClick={() => this.handleSearch(selectedKeys, confirm, dataIndex)}
                        icon={<SearchOutlined />}
                        size="small"
                        style={{
                            width: 90,
                        }}
                    >
                        搜索
                    </Button>
                    <Button
                        onClick={() => clearFilters && this.handleReset(clearFilters, dataIndex)}
                        size="small"
                        style={{
                            width: 90,
                        }}
                    >
                        重置
                    </Button>
                    <Button
                        type="link"
                        size="small"
                        onClick={() => {
                            close();
                        }}
                    >
                        关闭
                    </Button>
                </Space>
            </div>
        ),
        filterIcon: (filtered) => (
            <SearchOutlined
                style={{
                    color: filtered ? '#1677ff' : undefined,
                }}
            />
        ),
        onFilterDropdownOpenChange: (visible) => {
            if (visible) {

            }
        },

        render: (text) =>
            text
    });
    handleSearch = (selectedKeys, confirm, dataIndex) => {
        const { searchInput, contractColumns, user } = this.state;
        searchInput[dataIndex] = selectedKeys[0];
        searchInput['Account_Name'] = window.data.Account.id
        const dataIndexArray = ['Account_Name', 'Header', 'ShipperInformationName', 'ContractDate',
            'Terms_and_Conditions', 'Currency', 'Subject', 'AccountOrderNo', 'id'];

        const typeArray = {};
        contractColumns.map(item => {
            typeArray[item.dataIndex] = item.type
        });
        getCrmByParam(dataIndexArray, typeArray, searchInput, user, "Sales_Orders").then((data) => {
            this.setState({
                contactData: data,
                searchInput: searchInput,
            })
        })
        confirm();
    };
    handleReset = (clearFilters, dataIndex) => {
        const { searchInput } = this.state;
        searchInput[dataIndex] = "";
        this.setState({
            searchInput: searchInput,
        })
        clearFilters();
    };
    handleCancel = () => {
        ZOHO.CRM.UI.Popup.close().then(() => {
            this.setState({ loading: false });
        });
    }

    render() {
        const {
            loading,
            modalVisible,
            screenHeight,
            contractColumns,
            contactData,
            selectedContractRowKeys,
            dataSource,
            column,
            selectedRowKeys
        } = this.state;
        // console.log(222, screenHeight)
        return (
            <div>
                <Spin spinning={loading}>
                    <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: 16 }}>
                        <div>
                            <Button disabled={loading} onClick={this.handleSave} type="primary"
                                style={{ marginRight: 10 }}>
                                保存
                            </Button>
                            <Button style={{ marginLeft: 8, marginRight: 8 }} onClick={this.handleCancel}>
                                取消
                            </Button>
                        </div>
                    </div>
                    <div>
                        <Table
                            pagination={false}
                            rowSelection={{
                                fixed: true,
                                selectedRowKeys: selectedRowKeys, // 多选表格选中行的 keys 数组
                                onChange: this.onSelectChange, // 选中行发生变化时的回调函数
                            }}
                            rowKey="id"
                            dataSource={dataSource} columns={column} />
                        <Modal
                            open={modalVisible}
                            onCancel={this.handleModalClose}
                            onOk={this.handleOkModal}
                            cancelText={"关闭"}
                            style={{ top: 0, left: 0, right: 0, bottom: 0 }}
                            width="100%"
                            okText={"确认已挑选合同"}
                            centered
                        >
                            <Table
                                rowKey="id"
                                loading={loading}
                                rowSelection={{
                                    fixed: true,
                                    selectedRowKeys: selectedContractRowKeys, // 多选表格选中行的 keys 数组
                                    onChange: this.onContractSelectChange, // 选中行发生变化时的回调函数
                                }}
                                columns={contractColumns}
                                dataSource={contactData}
                                scroll={{ x: 200 }} />
                        </Modal>
                    </div>
                </Spin>
            </div>
        );
    }
}

export default LinkingModule9;